extends Node2D


const PREFAB_STAGES := [
    preload("res://scenes/stage/stage_01_streets.tscn"),
    preload("res://scenes/stage/stage_02_bar.tscn")
]


@onready var player: Player = $ActorsContainer/Player
@onready var stageContainer: Node2D = $StageContainer
@onready var actorsContainer: Node2D = $ActorsContainer
@onready var camera: Camera2D = $Camera
@onready var ui: UI = $UI


var current_stage_index: int = -1
var current_stage: Stage
var is_camera_locked: bool = false
# 摄像机初始位置，是为了切换关卡后重置摄像机位置
var camera_initial_position: Vector2 = Vector2.ZERO


func _init():
    StageManager.checkpoint_start.connect(on_checkpoint_start)
    StageManager.checkpoint_complete.connect(on_checkpoint_complete)
    StageManager.stage_complete.connect(on_stage_complete)
    StageManager.stage_interim.connect(on_stage_interim)


func _ready():
    camera_initial_position = camera.position
    load_next_stage()



func _process(_delta: float):
    if not is_camera_locked:
        if player.position.x > camera.position.x:
            camera.position.x = player.position.x


func load_next_stage():
    var index := clampi(current_stage_index + 1, 0, PREFAB_STAGES.size() - 1)
    if index == current_stage_index:
        return
    current_stage_index = index
    clear_stage()
    call_deferred("create_stage")


func clear_stage():
    for child: Node2D in stageContainer.get_children():
        child.queue_free()

    for child: Node2D in actorsContainer.get_children():
        if child is Player:
            continue
        child.queue_free()


func create_stage():
    current_stage = PREFAB_STAGES[current_stage_index].instantiate() as Stage
    stageContainer.add_child(current_stage)

    camera.position = camera_initial_position
    player.position = current_stage.get_player_spawn_location()

    camera.reset_smoothing()

    display_end_transition()


func display_end_transition():
    ui.stageTransition.end_transition()



func on_checkpoint_start():
    is_camera_locked = true


func on_checkpoint_complete(_checkpoint: Checkpoint):
    is_camera_locked = false



func on_stage_complete():
    ui.stageTransition.start_transition()


func on_stage_interim():
    load_next_stage()
